package io.github.eric.urpc.standalone.client;

import io.github.eric.urpc.client.Client;
import io.github.eric.urpc.core.util.RandomStringGenerator;
import io.github.eric.urpc.standalone.common.msg.IMMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ChatManager {
    private static final Logger LOGGER = LoggerFactory.getLogger(ChatManager.class);
    private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
    private Client client;
    private String userId;
    private String userName;
    private Random random = new Random();
    private MobileDevice mobileDevice;

    public ChatManager(Client client, MobileDevice mobileDevice, String userId, String userName) {
        this.client = client;
        this.mobileDevice = mobileDevice;
        this.userId = userId;
        this.userName = userName;
        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    startSendMessageToFriends();
                } catch (Exception e) {
                    LOGGER.error("schedule send message error", e);
                }
            }
        }, 1, 1, TimeUnit.SECONDS);
    }

    /**
     * 每秒钟选一个好友发送消息
     */
    public void startSendMessageToFriends() {
        List<String> allFriends = mobileDevice.getFriendManager().getAllFriends();
        if (allFriends == null || allFriends.isEmpty()) {
            return;
        }
        int index = random.nextInt(allFriends.size());
        String friend = allFriends.get(index);

        String content = RandomStringGenerator.genRandomString(20);
        IMMessage imMessage = new IMMessage();
        imMessage.setMessageId(userId + "-" + UUID.randomUUID());
        imMessage.setFromUserId(userName);
        imMessage.setToUserId(friend);
        imMessage.setContent(content);
//        LOGGER.info("向{}发消息: {}", friend, content);
        client.sendAsync(imMessage);
    }

}
